package com.hmdp.utils;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.BooleanUtil;
import com.hmdp.service.ILock;
import org.springframework.data.redis.core.StringRedisTemplate;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

public class SimpleRedisLock implements ILock {
    private String name;
    private StringRedisTemplate stringRedisTemplate;

    public SimpleRedisLock(String name, StringRedisTemplate stringRedisTemplate) {
        this.name = name;
        this.stringRedisTemplate = stringRedisTemplate;
    }

    private static final String PREFIX_NAME = "lock:";
    private static final String PREFIX_ID = UUID.randomUUID().toString(true) + "-";

    @Override
    public boolean tryLock(Long timeSec) {
        String threadName = PREFIX_ID + Thread.currentThread().getName();
        Boolean aBoolean = stringRedisTemplate.opsForValue()
                .setIfAbsent(PREFIX_NAME + name, threadName, timeSec, TimeUnit.MINUTES);
        //解决自动拆箱可能引发空指针的问题
        return BooleanUtil.isTrue(aBoolean);
    }

    @Override
    public void unLock() {
        String threadName = PREFIX_ID + Thread.currentThread().getName();
        String id = stringRedisTemplate.opsForValue().get(PREFIX_NAME + name);
        if (threadName.equals(id)) {
            stringRedisTemplate.delete(PREFIX_NAME + name);
        }

    }
}
